package com.mingtu.guards.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.mingtu.common.adapter.MyFragmentPagerAdapter;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.bean.EcDequiBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class EcHydroModuleFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.horizontal_scroll_view)
    HorizontalScrollView horizontalScrollView;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private List<String> tabList = new ArrayList<>();
    private int tabNum = 0;
    private List<RadioButton> radioButtons = new ArrayList<>();
    private int mCurrentTab;
    private float mCurrentPositionOffset;
    private int mLastScrollX;
    private ArrayList<EcDequiBean.DataBean> hydroDequiList = new ArrayList<>();
    private static final String ARG_PARAM1 = "param1";
    private int position = 0;

    public static EcHydroModuleFragment getInstance(ArrayList<EcDequiBean.DataBean> hydroDequiList) {
        EcHydroModuleFragment ef = new EcHydroModuleFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_PARAM1, hydroDequiList);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            hydroDequiList = (ArrayList<EcDequiBean.DataBean>) getArguments().getSerializable(ARG_PARAM1);
            tabNum = hydroDequiList.size();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ec_hydro_module;
    }

    @Override
    protected void initData() {
        for (int i = 0; i < hydroDequiList.size(); i++) {
            EcDequiBean.DataBean dataBean = hydroDequiList.get(i);
            String name = dataBean.getName();
            String devId = dataBean.getDevId();
            tabList.add(name);
            mFragments.add(EcHydroFragment.getInstance(devId));
        }


//        int position = getIntent().getIntExtra("position", 0);

        viewPager.setOffscreenPageLimit(mFragments.size());
        viewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), mFragments));
        viewPager.setCurrentItem(position);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());

        int space = getResources().getDimensionPixelSize(R.dimen.dp_15);
        int texSize = getResources().getDimensionPixelSize(R.dimen.sp_12);
        for (int i = 0; i < tabNum; i++) {
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            if (i < tabNum - 1) {
                lp.setMargins(space, 0, 0, 0);//设置边距
            }
            if (i == tabNum - 1) {
                lp.setMargins(space, 0, space, 0);//设置边距
            }

            int width = getResources().getDimensionPixelSize(R.dimen.dp_90);
            int height = getResources().getDimensionPixelSize(R.dimen.dp_27);

            RadioButton radioButton = new RadioButton(context);
            radioButton.setButtonDrawable(null);
            radioButton.setBackgroundResource(R.drawable.selector_radio_top_tab);
            radioButton.setText(tabList.get(i));
            radioButton.setWidth(width);
            radioButton.setHeight(height);
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, texSize);
            radioButton.setGravity(Gravity.CENTER);
            radioButton.setTextColor(context.getResources().getColorStateList(R.color.selector_radio_tab_text));
            radioButtons.add(radioButton);
            radioGroup.addView(radioButton, i, lp);
            if (i == 0) {
                radioButton.getPaint().setFakeBoldText(true);
            }

        }
        radioGroup.check(radioButtons.get(position).getId());


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int count = radioGroup.getChildCount();
                for (int j = 0; j < count; j++) {
                    RadioButton radioButton = (RadioButton) radioGroup.getChildAt(j);
                    if (radioButton.isChecked()) {
                        viewPager.setCurrentItem(j);
                        break;
                    }
                }
                for (int j = 0; j < radioGroup.getChildCount(); j++) {
                    RadioButton radioButton = (RadioButton) radioGroup.getChildAt(j);
                    boolean isChecked = radioButton.isChecked();
                    if (isChecked) {
                        radioButton.getPaint().setFakeBoldText(true);
                    } else {
                        radioButton.getPaint().setFakeBoldText(false);
                    }
                }
            }
        });
        calcIndicatorRect();

    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void getData() {

    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mCurrentTab = position;
            mCurrentPositionOffset = positionOffset;
            scrollToCurrentTab();
            horizontalScrollView.invalidate();
        }

        @Override
        public void onPageSelected(int position) {
            radioGroup.check(radioButtons.get(position).getId());
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private Rect mTabRect = new Rect();

    /**
     * HorizontalScrollView滚到当前tab,并且居中显示
     */
    private void scrollToCurrentTab() {
        int offset = (int) (mCurrentPositionOffset * (radioGroup.getChildAt(mCurrentTab).getWidth() + getResources().getDimensionPixelSize(R.dimen.dp_15)));
        /**当前Tab的left+当前Tab的Width乘以positionOffset*/
        int newScrollX = radioGroup.getChildAt(mCurrentTab).getLeft() + offset;

        if (mCurrentTab > 0 || offset > 0) {
            /**HorizontalScrollView移动到当前tab,并居中*/
            newScrollX -= horizontalScrollView.getWidth() / 2 - horizontalScrollView.getPaddingLeft();
            calcIndicatorRect();
            newScrollX += ((mTabRect.right - mTabRect.left) / 2);
        }

        if (newScrollX != mLastScrollX) {
            mLastScrollX = newScrollX;
            /** scrollTo（int x,int y）:x,y代表的不是坐标点,而是偏移量
             *  x:表示离起始位置的x水平方向的偏移量
             *  y:表示离起始位置的y垂直方向的偏移量
             */
            if (mCurrentTab == 0) {
                horizontalScrollView.scrollTo(newScrollX - getResources().getDimensionPixelSize(R.dimen.dp_15), 0);
            } else {
                horizontalScrollView.scrollTo(newScrollX - getResources().getDimensionPixelSize(R.dimen.dp_1), 0);
            }
        }
    }

    private void calcIndicatorRect() {
        View currentTabView = radioGroup.getChildAt(this.mCurrentTab);
        float left = currentTabView.getLeft();
        float right = currentTabView.getRight();
        if (this.mCurrentTab < radioGroup.getChildCount() - 1) {
            View nextTabView = radioGroup.getChildAt(this.mCurrentTab + 1);
            float nextTabLeft = nextTabView.getLeft();
            float nextTabRight = nextTabView.getRight();

            left = left + mCurrentPositionOffset * (nextTabLeft - left);
            right = right + mCurrentPositionOffset * (nextTabRight - right);

        }

        mTabRect.left = (int) left;
        mTabRect.right = (int) right;
    }


}